package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额数据统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合存放从begin到end范围内每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        log.info("日期:{},{}", begin, end);
//        end.plusDays(1);
//        do{
//            dataList.add(begin);
//            begin.plusDays(1);
//        }while(!begin.equals(end));
        //dataList.add(end);

        //LocalDate为不可变类型
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();

            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;

            turnoverList.add(turnover);
        }

        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();

    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        end = end.plusDays(1);
        do{
            dateList.add(begin);
            begin = begin.plusDays(1);
        }while(!begin.equals(end));

        List<Integer> orderList = new ArrayList<>();
        List<Integer> validOrderList = new ArrayList<>();
        int all = 0;
        int validAll = 0;
        double acc = 0.0;

        for(LocalDate date : dateList){
            LocalDateTime beginDate = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endDate = LocalDateTime.of(date, LocalTime.MAX);

            Integer num = getOrderCount(beginDate, endDate, null);
            Integer validNum = getOrderCount(beginDate, endDate, Orders.COMPLETED);

            validNum = validNum == null ? 0 : validNum;
            num = num == null ? 0 : num;
            orderList.add(num);
            validOrderList.add(validNum);
            //all += num;
            //validAll += validNum;
        }

        /*
        reduce()后会返回一个Optional<Integer>类型的值，使用get()会得到值，但如果为空会抛出NoSuchElementException 异常，
        可以替换为orElse(0)，避免异常的抛出
         */

        all = orderList.stream().reduce(Integer::sum).orElse(0);
        validAll = validOrderList.stream().reduce(Integer::sum).orElse(0);

        if(all != 0){
            acc = (double) validAll / (double) all *100.0;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderList, ","))
                .validOrderCountList(StringUtils.join(validOrderList, ","))
                .validOrderCount(validAll)
                .totalOrderCount(all)
                .orderCompletionRate(acc)
                .build();
    }

    /**
     * 销售量前十统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginDate = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endDate = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> list = orderMapper.getSalesTop10(beginDate, endDate);

        List<String> names = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> nums = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(nums, ","))
                .build();
    }

    /**
     * 统计总用户和本日新增用户
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        List<Integer> allUserList = new ArrayList<>();
        List<Integer> dailyUserList = new ArrayList<>();

        List<LocalDate> dateList = new ArrayList<>();
        end = end.plusDays(1);
        do{
            dateList.add(begin);
            begin = begin.plusDays(1);
        }while(!begin.equals(end));

        int all = userMapper.getByDateTime(null, LocalDateTime.of(dateList.get(0), LocalTime.MIN));
        for(LocalDate date : dateList){
            LocalDateTime start = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime ed = LocalDateTime.of(date, LocalTime.MAX);
            int num = userMapper.getByDateTime(start, ed);
            all += num;
            dailyUserList.add((Integer) num);
            allUserList.add((Integer) all);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(allUserList, ","))
                .newUserList(StringUtils.join(dailyUserList, ","))
                .build();
    }

    /**
     * 导出运营数据代码
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        XSSFWorkbook excel = null;
        try {
            excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("sheet1");

            sheet.getRow(1).getCell(1).setCellValue("日期: "+dateBegin + " 至 " + dateEnd);

            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            int idx = 7;
            dateEnd.plusDays(1);
            do{
                BusinessDataVO businessDataVO1 = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateBegin, LocalTime.MAX));
                row = sheet.getRow(idx);
                row.getCell(1).setCellValue(dateBegin.toString());
                row.getCell(2).setCellValue(businessDataVO1.getTurnover());
                row.getCell(3).setCellValue(businessDataVO1.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO1.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO1.getNewUsers());

                idx++;
                dateBegin = dateBegin.plusDays(1);

            }while(!dateBegin.equals(dateEnd));

            //3. 通过输入输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status){
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }

}
